<template>

	<div>
		<el-dialog :title="title" :visible.sync="dialogVisible" width="1000px" :before-close="handleClose"
			:close-on-click-modal="false">
			<el-form :inline="false" :model="formInline" ref="edd-add-form" :rules="formRules" class="demo-form-inline"
				v-loading="loadingForm" label-width="140px">
				<!-- <el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="上级分类:" prop="name">
							  <el-select v-model="formInline.duties" class="cell-input" placeholder="请选择上级分类">
							  	<el-option label="item.label" value="item.value" />
							  </el-select>
						</el-form-item>
					</el-col>
				</el-row> -->
				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="优惠券名称:" prop="couponName">
							<el-input v-model="formInline.couponName" class="cell-input" placeholder="请输入优惠卷名称">
							</el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="24">
						<el-form-item label="优惠券类型:" prop="couponType">
							<div>
								<el-radio v-model="formInline.couponType" label="1"
									@change="formInline.couponValue2 = ''">满减</el-radio>
								<span style="margin-left: 20px;">满 </span>
								<el-input placeholder="" v-model="formInline.minMonetary"
									:disabled="formInline.couponType!='1'" style="width:140px;" size="mini">
									<template slot="append">元</template>
								</el-input>
								<span style="margin-left: 20px;">，减 </span>
								<el-input placeholder="" v-model="formInline.couponValue1"
									:disabled="formInline.couponType!='1'" style="width:140px;" size="mini">
									<template slot="append">元</template>
								</el-input>
							</div>
							<div>
								<el-radio v-model="formInline.couponType" label="2"
									@change="formInline.minMonetary = '';formInline.couponValue1 = '';">直减</el-radio>
								<span style="margin-left: 20px;">减 </span>
								<el-input placeholder="" v-model="formInline.couponValue2"
									:disabled="formInline.couponType!='2'" style="width:140px;" size="mini">
									<template slot="append">元</template>
								</el-input>
							</div>
						</el-form-item>
						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="优惠券使用时间:" prop="validiteRadio">
									<div>
										<el-radio v-model="formInline.validiteRadio" label="1"
											@change="formInline.validity='';">指定时间 </el-radio>
										<el-date-picker v-model="formInline.validiteTime" type="daterange"
											:disabled="formInline.validiteRadio!='1'" size="mini"
											style="margin-left: 20px;" range-separator="至" start-placeholder="开始日期"
											end-placeholder="结束日期">
										</el-date-picker>
									</div>
									<div style="margin-top: 12px;">
										<el-radio v-model="formInline.validiteRadio" label="2"
											@change="formInline.validiteTime = []">领券后立即生效</el-radio>
										<span style="margin-left: 20px;">有效期 </span>
										<el-input placeholder="" v-model="formInline.validity" style="width:140px;"
											size="mini" :disabled="formInline.validiteRadio!='2'">
											<template slot="append">天</template>
										</el-input>
									</div>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="发放总量:" prop="distributionTimes">
									<el-input placeholder="" v-model="formInline.distributionTimes"
										style="width:140px;">
										<template slot="append">张</template>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="适用范围:" prop="useGoods">
									<el-radio v-model="formInline.useGoods" label="0">全部商品可用</el-radio>
									<el-radio v-model="formInline.useGoods" label="1">指定商品可用</el-radio>
									<div style="margin-top: 12px;" v-if="formInline.useGoods == '1'">
										<el-select v-model="formInline.goodsId" placeholder="请选择商品">
											<el-option v-for="(item,index) in goodsList" :key="index"
												:label="item.goodsName" :value="item.goodsId" />
										</el-select>
									</div>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="优惠券领取时间:" prop="times">
									<el-date-picker v-model="formInline.times" type="daterange" range-separator="至"
										start-placeholder="开始日期" end-placeholder="结束日期">
									</el-date-picker>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="领取次数限制:" prop="limitTimeState">
									<el-radio v-model="formInline.limitTimeState" label="0" @change="formInline.limitTime = ''">每人领取次数不限</el-radio>
									<el-radio v-model="formInline.limitTimeState" label="1" @change="formInline.limitTime = ''">每人最多可领</el-radio>
									<el-input placeholder="" v-model="formInline.limitTime"
										:disabled="formInline.limitTimeState != '1'" style="width:140px;" size="mini">
										<template slot="append">次</template>
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="领取用户限制:" prop="receiveUserType">
									<el-radio v-model="formInline.receiveUserType" label="0">全部用户可用</el-radio>
									<el-radio v-model="formInline.receiveUserType" label="1">指定用户角色可用</el-radio>
									<div style="margin-top: 12px;" v-if="formInline.receiveUserType == '1'">
										<el-button>选择用户</el-button>
									</div>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="优惠券叠加设置:" prop="issuperposition">
									<!-- <el-checkbox v-model="formInline.issuperposition">可叠加使用</el-checkbox> -->
									<el-radio v-model="formInline.issuperposition" label="0">不可叠加使用</el-radio>
									<el-radio v-model="formInline.issuperposition" label="1">可叠加使用</el-radio>
								</el-form-item>
							</el-col>
						</el-row>

						<el-row :gutter="20">
							<el-col :span="24">
								<el-form-item label="优惠券使用说明:" prop="f1">
									<el-input type="textarea" :autosize="{ minRows: 2, maxRows: 12}" placeholder="请输入内容"
										v-model="formInline.f1" :maxlength="500" :show-word-limit="true">
									</el-input>
								</el-form-item>
							</el-col>
						</el-row>

					</el-col>
				</el-row>
			</el-form>


			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleSubmit" :loading="btnLoading">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import {
		addWcCoupon,
		updataWcCoupon,
		findWcCoupon
	} from "@/api/culturalCreativity/coupon.js";
	import {
		listWcGoods
	} from "@/api/culturalCreativity/shopping.js";
	let _this;
	export default {
		name: "EaaAdd",
		data() {
			return {
				title: '',
				id: null,
				dialogVisible: false,
				formRules: {
					couponName: {
						required: true,
						message: '请输入优惠券名称',
						trigger: 'blur'
					},
					distributionTimes: {
						required: true,
						message: '请输入发放总量',
						trigger: 'blur'
					},
					useGoods: {
						required: true,
						message: '请选择适用范围',
						trigger: 'change'
					},
					times: {
						required: true,
						message: '请选择优惠券领取时间',
						trigger: 'change'
					},
					validiteRadio: {
						required: true,
						validator: (rule, value, callback) => {
							if (value == '1') {
								if (!this.formInline.validiteTime) return callback(new Error('请选择指定时间'));
								return callback();
							}
							if (value == '2') {
								if (!this.formInline.validity) return callback(new Error('请输入有效期'));
								return callback();
							}
							return callback(new Error('请选择优惠券使用时间'));
						},
						trigger: 'change'
					},
					couponType: {
						required: true,
						validator: (rule, value, callback) => {
							if (value == '1') {
								if (!this.formInline.couponValue1) return callback(new Error('请输入减多少元'));
								if (!this.formInline.minMonetary) return callback(new Error('请输入满多少元'));
								return callback();
							}
							if (value == '2') {
								if (!this.formInline.couponValue2) return callback(new Error('请输入减多少元'));
								return callback();
							}
							return callback(new Error('请选择优惠券类型'));
						},
						trigger: 'change'
					},
					limitTimeState: {
						required: true,
						validator: (rule, value, callback) => {
							if (value == '1') {
								if (!this.formInline.limitTime) return callback(new Error('请输入可领取次数'));
								return callback();
							}
							if (value == '0') return callback();
							return callback(new Error('请选择领取次数限制'));
						},
						trigger: 'change'
					},
					receiveUserType: {
						required: true,
						message: '请选择领取用户限制',
						trigger: 'change'
					},
					issuperposition: {
						required: true,
						message: '请选择优惠券叠加设置',
						trigger: 'change'
					},
				},
				formInline: {},
				loadingScreen: null,
				loadingForm: false,
				fileName: '',
				btnLoading: false,
				goodsList: [], //商品列表
			}
		},
		async mounted() {
			let res = await listWcGoods({
				pageNum: 1,
				pageSize: 99999,
			});
			this.goodsList = res.rows;
			console.log('查看商品列表：', res.rows)
		},
		methods: {
			async init(id) {
				try {
					_this = this;
					this.title = '';
					this.resetFrom();
					this.dialogVisible = true;
					if (this.$refs['edd-add-form']) this.$refs['edd-add-form'].resetFields();
					if (!id) return this.title = '新增';
					this.title = '修改'
					this.loadingForm = true;
					let res = await findWcCoupon(id);
					this.loadingForm = false;
					this.formInline.couponId = id;
					Object.keys(this.formInline).forEach(item => {
						this.formInline[item] = res.data[item];
					});
					this.formInline.times = [res.data.getCouponStartTime, res.data.getCouponEndTime];
					this.formInline.validiteTime = [res.data.validiteStart, res.data.validiteEnd];
					if (Number(res.data.couponType) == 1) this.formInline.couponValue1 = res.data.couponValue;
					if (Number(res.data.couponType) == 2) this.formInline.couponValue2 = res.data.couponValue;
					if (Number(res.data.couponType) == 2) this.formInline.minMonetary = "";
					if (this.formInline.validity) {
						this.formInline.validiteRadio = "2";
						this.formInline.validiteTime = [];
					} else {
						this.formInline.validiteRadio = "1";
						this.formInline.validity = "";
					}
					if (Number(this.formInline.limitTimeState) != 1) this.formInline.limitTime = "";
					this.formInline.goodsId = Number(this.formInline.goodsId);
				} catch (e) {
					this.loadingForm = false;
					//TODO handle the exception
				}
			},
			resetFrom() {
				this.formInline = {
					couponName: "",
					couponType: "",
					minMonetary: "",
					times: [], //领取 开始结束时间
					validiteTime: [], //有效期时间
					validity: "", //有效天数
					useGoods: "",
					issuperposition: "",
					f1: "",
					receiveUserType: "",
					distributionTimes: "",
					limitTimeState: "",
					limitTime: "",
					couponValue2: "",
					couponValue1: "",
					validiteRadio: "",
					goodsId:"",
					receiveUserRole:"1,2,3"
				}
			},
			handleClose() {
				this.dialogVisible = false;
			},
			handleUpFileChange(file) {
				if (file.response) {
					if (file.response.code == 200) {
						this.fileName = file.name;
						this.formInline.attachmentAddress = file.response.url;
						this.$refs['edd-add-form'].validateField('attachmentAddress');
					} else {
						this.fileName = '文件上传失败，请重新上传。'
					}
					this.loadingScreen.close();
				} else {
					this.loadingScreen = this.$loading({
						lock: true,
						text: '上传文件中...',
						spinner: 'el-icon-loading',
						background: 'rgba(0, 0, 0, 0.7)'
					});
				}
			},
			handleSubmit() {
				this.$refs['edd-add-form'].validate(async valid => {
					try {
						if (valid) {
							let formInline = {
								...this.formInline,
								getCouponStartTime: this.formInline.times[0] || "", //领取时间
								getCouponEndTime: this.formInline.times[1] || "", //结束时间
								validiteStart: this.formInline.validiteTime[0] || "", //使用开始时间
								validiteEnd: this.formInline.validiteTime[1] || "" //使用结束时间
							};
							if (formInline.couponType == '1') formInline.couponValue = formInline.couponValue1;
							if (formInline.couponType == '2') formInline.couponValue = formInline.couponValue2;
							delete formInline.times;
							delete formInline.validiteTime;
							delete formInline.validiteRadio;
							delete formInline.couponValue1;
							delete formInline.couponValue2;
							if (Number(formInline.limitTimeState) != 1) formInline.limitTime = 999999;
							let res;
							this.btnLoading = true;
							if (!formInline.couponId) {
								res = await addWcCoupon(formInline);
								this.$message.success("添加成功");
							} else {
								res = await updataWcCoupon(formInline);
								this.$message.success("更新成功");
							}
							this.btnLoading = false;
							this.dialogVisible = false;
							this.$emit("success");
						}
					} catch (e) {
						this.btnLoading = false;
					}
				});
			},
			handleReasonListDel(index) {
				let arr = this.formInline.list;
				this.formInline.list = [...arr.slice(0, index), ...arr.slice(index + 1, arr.length)];
				this.$refs['edd-add-form'].validateField('reason');
			},
			handleReasonListAdd() {
				this.formInline.list.push({
					holidays: this.otherValue,
					dayNumber: 1
				});
				this.$refs['edd-add-form'].validateField('reason');
			}
		},
		created() {
			this.resetFrom();
		},
		computed: {}
	}
</script>
<style lang="scss" scoped>
	.width100 {
		width: 590px;
	}

	.cell-input {
		width: 200px;
	}

	.up-file-wrappar {
		display: flex;
		align-items: center;
	}

	.total-day {
		display: inline-block;
		height: 36px;
		width: 40px;
		margin: 0 6px;
		text-align: center;
		border-radius: 4px;
		border: 1px solid #DCDFE6;
		padding: 0 15px;
		box-sizing: border-box;
	}

	.up-file-name {
		display: inline-block;
		height: 36px;
		min-width: 555px;
		text-align: left;
		line-height: 36px;
		box-sizing: border-box;
		padding: 0 15px;
		border: 1px solid #DCDFE6;
		border-radius: 4px;
		color: #606266;
		font-size: inherit;

		.text {
			display: -webkit-box;
			overflow: hidden;
			white-space: normal !important;
			text-overflow: ellipsis;
			word-wrap: break-word;
			-webkit-line-clamp: 1; //行数
			-webkit-box-orient: vertical;
			max-width: 555px;
		}
	}
</style>
